package com.handpay.nocardpay.baselibrary.bill.view;

import android.graphics.Color;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import com.bigkoo.pickerview.OptionsPickerView;
import com.bigkoo.pickerview.TimePickerView;
import com.handpay.nocardpay.baselibrary.R;
import com.handpay.nocardpay.baselibrary.bill.model.adapter.QueryBillAdapter;
import com.handpay.nocardpay.baselibrary.bill.model.bean.BillBean;
import com.handpay.nocardpay.baselibrary.bill.presenter.BillPresenterImpl;
import com.handpay.nocardpay.baselibrary.commbase.BaseProtocolKey;
import com.handpay.nocardpay.baselibrary.commbase.view.fragment.BaseFragment;
import com.handpay.nocardpay.baselibrary.logutils.HPLog;
import com.handpay.nocardpay.baselibrary.utils.ClientEngine;
import com.handpay.nocardpay.baselibrary.utils.CommonUtils;
import com.handpay.nocardpay.baselibrary.utils.DialogUtils;
import com.handpay.nocardpay.baselibrary.utils.NoCardPayConstant;
import com.handpay.nocardpay.baselibrary.widget.CustomTextView;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

/**
 * Created by sxshi on 2017/8/9.
 */

public class BillFragment extends BaseFragment implements IBillView<BillBean> {
    private View mHeaderView;
    private View mFooterView;

    private ListView mListView;

    private QueryBillAdapter billAdapter;
    private BillPresenterImpl billPresenter;

    private TimePickerView startTimePicker;
    private TimePickerView endTimePicker;

    private OptionsPickerView tradeStatusPicker, tradeTypePicker;
    //显示的交易方式、交易状态的值。
    private List<String> tradeStatus, tradeTypes;

    //根据关键字获取对应的值
    private HashMap<String, String> mapTradeStatus;
    private HashMap<String, String> mapTradeType;
    private Date startTransDate, endTransDate;

    //hearder view
    private CustomTextView ctv_start_date, ctv_end_date, ctv_tradestatus, ctv_tradetype;
    private EditText et_serialno;
    private Button btn_query;
    private TextView tv_total_money, tv_total_item;
    private LinearLayout ll_footerinfo;

    //footer view
    private TextView tv_index_page, tv_total_page, tv_home, tv_prepage, tv_nextpage, tv_lastpage;
    private int pageNo = 1;
    private int totalPages = -1;
    private String tradeTypeValue;
    private String tradeStatusValue;

    public static BillFragment newInstance() {
        Bundle args = new Bundle();
        BillFragment fragment = new BillFragment();
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public int getLayoutId() {
        return R.layout.fragment_bill;
    }

    @Override
    public String getFragmentTitle() {
        return getString(R.string.query_bill);
    }

    @Override
    public void initView(View view) {
        Toolbar mToolbar = (Toolbar) view.findViewById(R.id.toolbar);
        initToolbar(mToolbar, true);

        mListView = (ListView) view.findViewById(R.id.lv_serialno);
        mHeaderView = LayoutInflater.from(_mActivity).inflate(R.layout.item_billhead, null);
        mFooterView = LayoutInflater.from(_mActivity).inflate(R.layout.item_billfoot, null);

        //init header's view
        ctv_start_date = (CustomTextView) mHeaderView.findViewById(R.id.ctv_start_date);
        ctv_end_date = (CustomTextView) mHeaderView.findViewById(R.id.ctv_end_date);
        ctv_tradestatus = (CustomTextView) mHeaderView.findViewById(R.id.ctv_tradestatus);
        ctv_tradetype = (CustomTextView) mHeaderView.findViewById(R.id.ctv_tradetype);
        et_serialno = (EditText) mHeaderView.findViewById(R.id.et_serialno);
        btn_query = (Button) mHeaderView.findViewById(R.id.btn_query);
        tv_total_money = (TextView) mHeaderView.findViewById(R.id.tv_total_money);
        tv_total_item = (TextView) mHeaderView.findViewById(R.id.tv_total_item);
        ll_footerinfo = (LinearLayout) mHeaderView.findViewById(R.id.ll_footerinfo);
        //init footer's view
        tv_index_page = (TextView) mFooterView.findViewById(R.id.tv_index_page);
        tv_total_page = (TextView) mFooterView.findViewById(R.id.tv_total_page);
        tv_home = (TextView) mFooterView.findViewById(R.id.tv_home);
        tv_prepage = (TextView) mFooterView.findViewById(R.id.tv_prepage);
        tv_nextpage = (TextView) mFooterView.findViewById(R.id.tv_nextpage);
        tv_lastpage = (TextView) mFooterView.findViewById(R.id.tv_lastpage);

        initTimePicker();
        initOptionsPicker();
    }

    private void initOptionsPicker() {
        tradeTypePicker = new OptionsPickerView.Builder(_mActivity, new OptionsPickerView.OnOptionsSelectListener() {
            @Override
            public void onOptionsSelect(int options1, int options2, int options3, View v) {
                pageNo = 1;
                String tradeTypeKey = tradeTypes.get(options1);
                tradeTypeValue = mapTradeType.get(tradeTypeKey);
                HPLog.d(HPLog.SSX_TAG, tradeTypeKey + ":" + tradeTypeValue);
                ctv_tradetype.setLeftTv(tradeTypeKey, null);
            }
        }).setDecorView(null)
                .setContentTextSize(21)
                .build();
        tradeStatusPicker = new OptionsPickerView.Builder(_mActivity, new OptionsPickerView.OnOptionsSelectListener() {
            @Override
            public void onOptionsSelect(int options1, int options2, int options3, View v) {
                pageNo = 1;
                String tradeStatusKey = tradeStatus.get(options1);
                tradeStatusValue = mapTradeStatus.get(tradeStatusKey);
                HPLog.d(HPLog.SSX_TAG, tradeStatusKey + ":" + tradeStatusValue);
                ctv_tradestatus.setLeftTv(tradeStatus.get(options1), null);
            }
        }).setDecorView(null)
                .setContentTextSize(21)
                .build();
    }

    @Override
    public void initListener() {
        ctv_start_date.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startTimePicker.show();
            }
        });
        ctv_end_date.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                endTimePicker.show();
            }
        });
        ctv_tradestatus.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                tradeStatusPicker.show();
            }
        });
        ctv_tradetype.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                tradeTypePicker.show();
            }
        });

        btn_query.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                pageNo = 1;
                queryBills(pageNo);
            }
        });
        tv_home.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                pageNo = 1;
                queryBills(1);
            }
        });
        tv_prepage.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                pageNo--;
                if (pageNo < 1) {
                    pageNo = 1;
                }
                queryBills(pageNo);
            }
        });
        tv_nextpage.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                pageNo++;
                if (pageNo > totalPages) {
                    pageNo = totalPages;
                }
                queryBills(pageNo);
            }
        });
        tv_lastpage.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                pageNo = totalPages;
                queryBills(totalPages);
            }
        });
    }

    /**
     * 初始化时间控件
     */
    private void initTimePicker() {
        //控制时间范围(如果不设置范围，则使用默认时间1900-2100年，此段代码可注释)
        //因为系统Calendar的月份是从0-11的,所以如果是调用Calendar的set方法来设置时间,月份的范围也要是从0-11
        Calendar startSelectedDate = Calendar.getInstance();
        Calendar endSelectedDate = Calendar.getInstance();
        startSelectedDate.set(Calendar.HOUR_OF_DAY, 0);//24小时计时
        startSelectedDate.set(Calendar.MINUTE, 0);
        startSelectedDate.set(Calendar.SECOND, 0);
        endSelectedDate.set(Calendar.HOUR_OF_DAY, 23);//24小时计时
        endSelectedDate.set(Calendar.MINUTE, 59);
        endSelectedDate.set(Calendar.SECOND, 59);
        Calendar startDate = Calendar.getInstance();
        startDate.set(2007, 0, 23);
        final Calendar endDate = Calendar.getInstance();
        endDate.set(2019, 11, 28);
        //起始时间
        startTimePicker = new TimePickerView.Builder(_mActivity, new TimePickerView.OnTimeSelectListener() {
            @Override
            public void onTimeSelect(Date date, View v) {//选中事件回调
                pageNo = 1;
                startTransDate = date;
                ctv_start_date.setLeftTv(CommonUtils.formatDateToString(startTransDate, "yyyy-MM-dd"), null);
            }
        })
                //年月日时分秒 的显示与否，不设置则默认全部显示
                .setType(new boolean[]{true, true, true, false, false, false})
                .setLabel("", "", "", "", "", "")
                .isCenterLabel(false)
                .setDividerColor(Color.DKGRAY)
                .setContentSize(21)
                .setDate(startSelectedDate)
                .setRangDate(startDate, endDate)
//                .setBackgroundId(0x00FFFFFF) //设置外部遮罩颜色
                .setDecorView(null)
                .build();

//        结束时间
        endTimePicker = new TimePickerView.Builder(_mActivity, new TimePickerView.OnTimeSelectListener() {
            @Override
            public void onTimeSelect(Date date, View v) {//选中事件回调
                pageNo = 1;
                endTransDate = date;
                ctv_end_date.setLeftTv(CommonUtils.formatDateToString(date, "yyyy-MM-dd"), null);
            }
        })
                //年月日时分秒 的显示与否，不设置则默认全部显示
                .setType(new boolean[]{true, true, true, false, false, false})
                .setLabel("", "", "", "", "", "")
                .isCenterLabel(false)
                .setDividerColor(Color.DKGRAY)
                .setContentSize(21)
                .setDate(endSelectedDate)
                .setRangDate(startDate, endDate)
//                .setBackgroundId(0x00FFFFFF) //设置外部遮罩颜色
                .setDecorView(null)
                .build();

        //用户没有选择日期的时候使用当前日期作为默认值
        startTransDate = startSelectedDate.getTime();
        endTransDate = endSelectedDate.getTime();
        ctv_end_date.setLeftTv(CommonUtils.currentDate(startSelectedDate, "yyyy-MM-dd"), null);
        ctv_start_date.setLeftTv(CommonUtils.currentDate(endSelectedDate, "yyyy-MM-dd"), null);
    }

    /**
     * 分页查询
     *
     * @param currentPage
     */
    private void queryBills(int currentPage) {
        HashMap<String, Object> paramers = new HashMap<>();
        paramers.put(BaseProtocolKey.PAGESIZE, "5");
        paramers.put(BaseProtocolKey.PAGENO, currentPage);
        paramers.put(BaseProtocolKey.CHANNEL, ClientEngine.getInstance().CHANNEL);
        paramers.put(BaseProtocolKey.APPCODE, BaseProtocolKey.APPCODE_TRANSFER); // 应用代码 ASCII字符
        if (!TextUtils.isEmpty(tradeTypeValue)) {
            paramers.put(BaseProtocolKey.TRADETYPE, tradeTypeValue); // 交易类型
        }
        if (!TextUtils.isEmpty(tradeStatusValue)) {
            paramers.put(BaseProtocolKey.STATUS, tradeStatusValue); // 交易状态
        }

        if (startTransDate.after(endTransDate)) {
            DialogUtils.showAlertDialog(_mActivity, getString(R.string.dialog_title), getString(R.string.date_error), false);
            return;
        }
        if (!CommonUtils.equalsDate(startTransDate, endTransDate)) {
            DialogUtils.showAlertDialog(_mActivity, getString(R.string.dialog_title), getString(R.string.date_bigger), false);
            return;
        }
        //添加默认日期的值
        paramers.put(BaseProtocolKey.STARTTIME, CommonUtils.formatDateToString(startTransDate, "yyyyMMddHHmmss"));
        paramers.put(BaseProtocolKey.ENDTIME, CommonUtils.formatDateToString(endTransDate, "yyyyMMddHHmmss"));
        String transNo = et_serialno.getText().toString();
        if (!TextUtils.isEmpty(transNo)) {
            //解决输入流水单号超出Integer的最大值的情况
            if (Double.valueOf(transNo) >= Integer.MAX_VALUE) {
                DialogUtils.showAlertDialog(_mActivity, getString(R.string.tip), getString(R.string.hint_transno), false);
                return;
            }
            paramers.put(BaseProtocolKey.TRANSSN, transNo); // 交易流水
        } else {
            paramers.remove(BaseProtocolKey.TRANSSN);
        }
        billPresenter.queryBills(paramers, true);
    }

    @Override
    public void initData(Bundle savedInstanceState) {
        //交易状态
        tradeStatus = new ArrayList<>();
        mapTradeStatus = new HashMap<>();
        tradeStatus.add(getString(R.string.all));
        tradeStatus.add(getString(R.string.status_success));
        tradeStatus.add(getString(R.string.status_fail));
        tradeStatus.add(getString(R.string.status_proce));
        mapTradeStatus.put(getString(R.string.status_success), NoCardPayConstant.TRADESTATUS_SUCCESS);
        mapTradeStatus.put(getString(R.string.status_fail), NoCardPayConstant.TRADESTATUS_FAIL);
        mapTradeStatus.put(getString(R.string.status_proce), NoCardPayConstant.TRADESTATUS_PROCESS);
        //交易方式
        tradeTypes = new ArrayList<>();
        mapTradeType = new HashMap<>();
        tradeTypes.add(getString(R.string.all));
        tradeTypes.add(getString(R.string.trade_uninonline));
        tradeTypes.add(getString(R.string.trade_uninonquick));
        tradeTypes.add(getString(R.string.trade_alipay));
        tradeTypes.add(getString(R.string.trade_weipay));
        tradeTypes.add(getString(R.string.trade_qqwallet));
        tradeTypes.add(getString(R.string.trade_uninonscanner));

        mapTradeType.put(getString(R.string.trade_alipay), NoCardPayConstant.TRADETYPE_ALIPAY);
        mapTradeType.put(getString(R.string.trade_uninonline), NoCardPayConstant.TRADETYPE_UNIONPAYONLINE);
        mapTradeType.put(getString(R.string.trade_uninonquick), NoCardPayConstant.TRADETYPE_UNIONPAYQUICK);
        mapTradeType.put(getString(R.string.trade_weipay), NoCardPayConstant.TRADETYPE_WECHATPAY);
        mapTradeType.put(getString(R.string.trade_uninonscanner), NoCardPayConstant.TRADETYPE_UNIONSCANPAY);
        mapTradeType.put(getString(R.string.trade_qqwallet), NoCardPayConstant.TRADETYPE_QQWALLET);


        tradeTypePicker.setPicker(tradeTypes);
        tradeTypePicker.setSelectOptions(0);
        tradeStatusPicker.setPicker(tradeStatus);
        tradeStatusPicker.setSelectOptions(0);
        billAdapter = new QueryBillAdapter(_mActivity);
        billPresenter = new BillPresenterImpl(_mActivity);
        billPresenter.setBillView(this);
        mListView.addHeaderView(mHeaderView);
        mListView.addFooterView(mFooterView);
        mListView.setAdapter(billAdapter);
    }

    @Override
    public void showBills(BillBean billBean) {
        billAdapter.clear();
        if (!billBean.getList().isEmpty()) {
            billAdapter.setmLists(billBean.getList());
            totalPages = Integer.valueOf(billBean.getTotalPages());
            ll_footerinfo.setVisibility(View.VISIBLE);
            if (totalPages > 1) {
                mFooterView.setVisibility(View.VISIBLE);
            } else {
                mFooterView.setVisibility(View.GONE);
            }
            if (pageNo <= 1) {
                tv_prepage.setEnabled(false);
                tv_home.setEnabled(false);
            } else {
                tv_prepage.setEnabled(true);
                tv_home.setEnabled(true);
            }
            if (pageNo >= totalPages) {
                tv_nextpage.setEnabled(false);
                tv_lastpage.setEnabled(false);
            } else {
                tv_nextpage.setEnabled(true);
                tv_lastpage.setEnabled(true);
            }

            tv_index_page.setText(String.format(getString(R.string.index_page), pageNo + ""));
            tv_total_page.setText(String.format(getString(R.string.total_page), totalPages + ""));

            Double amounts = Double.valueOf(billBean.getAmounts());
            String items = String.format(getString(R.string.total_items), billBean.getItems());
            String totalMoney = String.format(getString(R.string.total_money), CommonUtils.formatMoney(amounts / 100));

            tv_total_item.setText(CommonUtils.changeTextColor(items, 3, items.length()));
            tv_total_money.setText(CommonUtils.changeTextColor(totalMoney, 3, totalMoney.length()));

        } else {
            DialogUtils.showAlertDialog(_mActivity, getString(R.string.dialog_title), getString(R.string.no_bill_data), false);
            mFooterView.setVisibility(View.GONE);
            ll_footerinfo.setVisibility(View.GONE);
        }
    }
}
